﻿using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using MinimalistFoodStreet.BackEnd.Api.Api;
using MinimalistFoodStreet.BackEnd.Api.Api.Controllers;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.IServer;
using Newtonsoft.Json;

namespace JoyfulHomeJourney.BackEnd.Api.Admin.Filters
{
    // 使用前必须先检查登录否则不添加
    public class ActionLogFilter : IResultFilter
    {
        private readonly ILogServer _logServer;
        public ActionLogFilter(ILogServer logServer)
        {
            _logServer = logServer;
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {
        }

        // 代码在结果执行之前执行
        public async void OnResultExecuting(ResultExecutingContext context)
        {
            // 检查控制器方法是否包含指定特性
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var attr = action.MethodInfo.GetCustomAttribute<ActionLogAttribute>();
            if (attr == null)
                return;//无需记录
            // 检查是否包含数据
            var result = ((ObjectResult)context.Result)?.Value;
            if (result == null)
                return;
            // 消息
            var message = attr.Message;
            // 获取 HttpContext
            var httpContext = context.HttpContext;
            // 获取请求参数
            string requestParames = "";
            foreach (var key in httpContext.Request.Query.Keys)
            {
                requestParames += key + "=" + httpContext.Request.Query[key] + "&";
            }

            // 如果需要获取表单数据或 JSON 数据
            if (httpContext.Request.HasFormContentType)
            {
                var formCollection = httpContext.Request.Form;
                // 使用 formCollection 获取表单数据
                foreach (var key in formCollection.Keys)
                {
                    requestParames += key + "=" + formCollection[key] + "&";
                }
            }
            else if (httpContext.Request.ContentType.StartsWith("application/json"))
            {
                // 读取 JSON 请求体
                var requestBody = httpContext.Request.Body;
                requestBody.Position = 0;
                using (var reader = new StreamReader(requestBody))
                {
                    var bodyText = await reader.ReadToEndAsync();
                    requestParames += bodyText;
                }
            }
            // 用户编号
            var controller = context.Controller as BaseController;
            if (controller._account == null) return;
            // 受影响的行数
            ResponseApiDto responseApiDto = JsonConvert.DeserializeObject<ResponseApiDto>(result.ToString());
            _logServer.AddActionLog(new ActionLog
            {
                AlRequestParams = requestParames,
                AlIp = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "",
                AlRequestMethod = httpContext.Request.Method,
                AlAffectedRows = responseApiDto?.affectedRows ?? 0,
                AlRequestUrl = context.HttpContext.Request.Scheme + "://" + context.HttpContext.Request.Host + context.HttpContext.Request.Path,
                AlAccountId = controller._account.AId,
                AlMessage = message
            });

        }
    }
}

